package top.huacc.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.huacc.codeing.AdvancedImagePrinter;
import top.huacc.aliyun.facebody.FaceFusionUtils;

import javax.imageio.ImageIO;
import javax.print.PrintService;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@RestController
@RequestMapping("/api/print")
public class ImagePrintController {

    /**
     * 获取系统可用的打印机列表
     *
     * @return 打印机名称列表
     * @path: /api/print/printers
     */
    @GetMapping("/printers")
    public ResponseEntity<List<String>> getAvailablePrinters() {
        List<String> printerNames = new ArrayList<>();
        PrintService[] services = PrinterJob.lookupPrintServices();
        for (PrintService service : services) {
            printerNames.add(service.getName());
        }
        return ResponseEntity.ok(printerNames);
    }

    /**
     * 人体分割处理
     *
     * @param image           上传的图片文件
     * @param accessKeyId     阿里云访问密钥ID
     * @param accessKeySecret 阿里云访问密钥Secret
     * @return 分割后的图片URL
     * @path /api/print/human-body-segmentation
     */
    @PostMapping("/human-body-segmentation")
    public ResponseEntity<String> humanBodySegmentation(
            @RequestParam("image") MultipartFile image,
            @RequestParam(value = "accessKeyId", required = false) String accessKeyId,
            @RequestParam(value = "accessKeySecret", required = false) String accessKeySecret) {
        try (java.io.InputStream inputStream = image.getInputStream()) {
            // 检查文件是否为空
            if (image.isEmpty()) {
                return ResponseEntity.badRequest().body("上传的图片文件为空");
            }

            // 如果没有提供AK信息，则使用默认的
            if (accessKeyId == null || accessKeySecret == null) {
                accessKeyId = "LTAI5tQ4tDTGdWCgyBTtHZRV";
                accessKeySecret = "2j6y3biFywr2COGUojB9hchmv4IgQL";
            }

            // 调用人体分割工具方法
            String resultUrl = FaceFusionUtils.humanBodySegmentation(inputStream, accessKeyId, accessKeySecret);
            return ResponseEntity.ok(resultUrl);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("人体分割处理失败: " + e.getMessage());
        }
    }

    /**
     * 人体分割处理 (Base64版本)
     *
     * @param base64Image     base64编码的图片数据
     * @param accessKeyId     阿里云访问密钥ID
     * @param accessKeySecret 阿里云访问密钥Secret
     * @return 分割后的图片URL
     * @path /api/print/human-body-segmentation-base64
     */
    @PostMapping("/human-body-segmentation-base64")
    public ResponseEntity<String> humanBodySegmentationBase64(
            @RequestParam("image") String base64Image,
            @RequestParam(value = "accessKeyId", required = false) String accessKeyId,
            @RequestParam(value = "accessKeySecret", required = false) String accessKeySecret) {
        try {
            // 检查base64数据是否为空
            if (base64Image == null || base64Image.isEmpty()) {
                return ResponseEntity.badRequest().body("上传的图片数据为空");
            }

            // 解码base64数据
            byte[] imageBytes = Base64.getDecoder().decode(base64Image);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);

            // 如果没有提供AK信息，则使用默认的
            if (accessKeyId == null || accessKeySecret == null) {
                accessKeyId = "LTAI5tQ4tDTGdWCgyBTtHZRV";
                accessKeySecret = "2j6y3biFywr2COGUojB9hchmv4IgQL";
            }

            // 调用人体分割工具方法
            String resultUrl = FaceFusionUtils.humanBodySegmentation(inputStream, accessKeyId, accessKeySecret);
            return ResponseEntity.ok(resultUrl);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body("图片数据格式不正确，不是有效的base64编码");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("人体分割处理失败: " + e.getMessage());
        }
    }

    /**
     * 人体分割处理 (URL版本)
     *
     * @param imageUrl        图片URL
     * @param accessKeyId     阿里云访问密钥ID
     * @param accessKeySecret 阿里云访问密钥Secret
     * @return 分割后的图片URL
     * @path /api/print/human-body-segmentation-url
     */
    @PostMapping("/human-body-segmentation-url")
    public ResponseEntity<String> humanBodySegmentationUrl(
            @RequestParam("image") String imageUrl,
            @RequestParam(value = "accessKeyId", required = false) String accessKeyId,
            @RequestParam(value = "accessKeySecret", required = false) String accessKeySecret) {
        try {
            // 检查URL是否为空
            if (imageUrl == null || imageUrl.isEmpty()) {
                return ResponseEntity.badRequest().body("图片URL为空");
            }

            // 如果没有提供AK信息，则使用默认的
            if (accessKeyId == null || accessKeySecret == null) {
                accessKeyId = "LTAI5tQ4tDTGdWCgyBTtHZRV";
                accessKeySecret = "2j6y3biFywr2COGUojB9hchmv4IgQL";
            }

            // 调用人体分割工具方法
            String resultUrl = FaceFusionUtils.humanBodySegmentation(imageUrl, accessKeyId, accessKeySecret);
            return ResponseEntity.ok(resultUrl);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("人体分割处理失败: " + e.getMessage());
        }
    }

    /**
     * 上传图片并直接打印
     *
     * @param image       图片文件
     * @param printerName 打印机名称
     * @param copies      打印份数（可选，默认1份）
     * @param printMode   打印模式：normal(普通), 6inch_vertical(6寸竖向), 6inch_horizontal(6寸横向), custom(自定义尺寸)
     * @param fitToPage   是否适应页面（可选，默认true）
     * @param paperWidth  相纸宽度（英寸，可选）
     * @param paperHeight 相纸高度（英寸，可选）
     * @param dpi         打印分辨率（可选，默认300）
     * @return 打印结果
     */
    @PostMapping("/image")
    public ResponseEntity<String> printImage(
            @RequestParam("image") MultipartFile image,
            @RequestParam("printerName") String printerName,
            @RequestParam(value = "copies", defaultValue = "1") int copies,
            @RequestParam(value = "printMode", defaultValue = "normal") String printMode,
            @RequestParam(value = "fitToPage", defaultValue = "true") boolean fitToPage,
            @RequestParam(value = "paperWidth", required = false) Double paperWidth,
            @RequestParam(value = "paperHeight", required = false) Double paperHeight,
            @RequestParam(value = "dpi", defaultValue = "300") Integer dpi) {

        // 使用try-with-resources确保InputStream正确关闭
        try (java.io.InputStream inputStream = image.getInputStream()) {
            // 检查文件是否为空
            if (image.isEmpty()) {
                return ResponseEntity.badRequest().body("上传的图片文件为空");
            }
            // 将MultipartFile转换为BufferedImage
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            if (bufferedImage == null) {
                return ResponseEntity.badRequest().body("无法读取图片文件");
            }
            // 创建打印器实例
            AdvancedImagePrinter printer = new AdvancedImagePrinter(bufferedImage);
            printer.setCopies(copies);

            // 根据打印模式设置参数
            switch (printMode.toLowerCase()) {
                case "6inch_vertical":
                    // 6寸竖向照片打印
                    printer.set6InchPhoto(true);
                    break;
                case "6inch_horizontal":
                    // 6寸横向照片打印
                    printer.set6InchPhoto(false);
                    break;
                case "custom":
                    // 自定义尺寸打印
                    if (paperWidth != null && paperHeight != null) {
                        printer.setPaperSize(paperWidth, paperHeight, dpi);
                        printer.setNoBorder(true);
                        printer.setFitToPage(false);
                    } else {
                        return ResponseEntity.badRequest().body("自定义尺寸模式需要提供paperWidth和paperHeight参数");
                    }
                    break;
                case "normal":
                default:
                    // 普通打印模式
                    printer.setFitToPage(fitToPage);
                    if (paperWidth != null && paperHeight != null) {
                        printer.setPaperSize(paperWidth, paperHeight, dpi);
                    }
                    break;
            }

            // 执行打印
            printImageToSpecificPrinter(printer, printerName);
            return ResponseEntity.ok("图片已成功发送到打印机: " + printerName);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("打印失败: " + e.getMessage());
        }
    }

    /**
     * 上传base64编码的图片并直接打印
     *
     * @param base64Image base64编码的图片数据
     * @param printerName 打印机名称
     * @param copies      打印份数（可选，默认1份）
     * @param printMode   打印模式：normal(普通), 6inch_vertical(6寸竖向), 6inch_horizontal(6寸横向), custom(自定义尺寸)
     * @param fitToPage   是否适应页面（可选，默认true）
     * @param paperWidth  相纸宽度（英寸，可选）
     * @param paperHeight 相纸高度（英寸，可选）
     * @param dpi         打印分辨率（可选，默认300）
     * @path /api/print/image-base64
     * @return 打印结果
     */
    @PostMapping("/image-base64")
    public ResponseEntity<String> printImageBase64(
            @RequestParam("image") String base64Image,
            @RequestParam("printerName") String printerName,
            @RequestParam(value = "copies", defaultValue = "1") int copies,
            @RequestParam(value = "printMode", defaultValue = "normal") String printMode,
            @RequestParam(value = "fitToPage", defaultValue = "true") boolean fitToPage,
            @RequestParam(value = "paperWidth", required = false) Double paperWidth,
            @RequestParam(value = "paperHeight", required = false) Double paperHeight,
            @RequestParam(value = "dpi", defaultValue = "300") Integer dpi) {

        try {
            // 检查base64数据是否为空
            if (base64Image == null || base64Image.isEmpty()) {
                return ResponseEntity.badRequest().body("上传的图片数据为空");
            }

            // 解码base64数据
            byte[] imageBytes = Base64.getDecoder().decode(base64Image);
            BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imageBytes));

            if (bufferedImage == null) {
                return ResponseEntity.badRequest().body("无法读取图片数据");
            }

            // 创建打印器实例
            AdvancedImagePrinter printer = new AdvancedImagePrinter(bufferedImage);
            printer.setCopies(copies);

            // 根据打印模式设置参数
            switch (printMode.toLowerCase()) {
                case "6inch_vertical":
                    // 6寸竖向照片打印
                    printer.set6InchPhoto(true);
                    break;
                case "6inch_horizontal":
                    // 6寸横向照片打印
                    printer.set6InchPhoto(false);
                    break;
                case "custom":
                    // 自定义尺寸打印
                    if (paperWidth != null && paperHeight != null) {
                        printer.setPaperSize(paperWidth, paperHeight, dpi);
                        printer.setNoBorder(true);
                        printer.setFitToPage(false);
                    } else {
                        return ResponseEntity.badRequest().body("自定义尺寸模式需要提供paperWidth和paperHeight参数");
                    }
                    break;
                case "normal":
                default:
                    // 普通打印模式
                    printer.setFitToPage(fitToPage);
                    if (paperWidth != null && paperHeight != null) {
                        printer.setPaperSize(paperWidth, paperHeight, dpi);
                    }
                    break;
            }

            // 执行打印
            printImageToSpecificPrinter(printer, printerName);
            return ResponseEntity.ok("图片已成功发送到打印机: " + printerName);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body("图片数据格式不正确，不是有效的base64编码");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("打印失败: " + e.getMessage());
        }
    }

    /**
     * 打印到指定名称的打印机
     *
     * @param printer     AdvancedImagePrinter实例
     * @param printerName 打印机名称
     * @throws PrinterException 打印异常
     */
    private void printImageToSpecificPrinter(AdvancedImagePrinter printer, String printerName)
            throws PrinterException {
        PrinterJob printJob = PrinterJob.getPrinterJob();
        printJob.setPrintable(printer);
        // 设置打印份数
        printJob.setCopies(printer.getCopies());

        // 查找指定名称的打印机
        PrintService[] services = PrinterJob.lookupPrintServices();
        PrintService targetService = null;
        for (PrintService service : services) {
            if (service.getName().equals(printerName)) {
                targetService = service;
                break;
            }
        }
        if (targetService == null) {
            throw new PrinterException("未找到名称为 '" + printerName + "' 的打印机");
        }
        // 设置指定的打印机
        printJob.setPrintService(targetService);

        // 检查是否需要设置自定义页面格式（用于相纸尺寸）
        if (printer.getPaperWidth() > 0 && printer.getPaperHeight() > 0) {
            PageFormat pageFormat = printJob.defaultPage();
            // 设置页面尺寸为整个相纸尺寸（转换为点）
            double paperWidthPoints = printer.getPaperWidth() * 72;   // 转换为点 (1英寸 = 72点)
            double paperHeightPoints = printer.getPaperHeight() * 72;
            Paper paper = new Paper();
            paper.setSize(paperWidthPoints, paperHeightPoints);
            // 设置可打印区域为整个纸张，实现真正的无边框
            paper.setImageableArea(0, 0, paperWidthPoints, paperHeightPoints);
            pageFormat.setPaper(paper);
            printJob.setPrintable(printer, pageFormat);
        }

        // 直接打印，无需用户确认
        printJob.print();
    }
}